package com.skytech.component.monitor.enterprise_data_monitoring;

import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.data.MonitorDataTag;
import com.skytech.component.monitor.data.MonitorDataTagDAO;
import com.skytech.component.monitor.util.FormateConnection;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static java.lang.Integer.parseInt;

@Service
public class BeiJingService implements CrawlerScript {
    private static final String province = "北京";


    @Autowired
    private MonitorDataTagDAO monitorDataTagDAO;

    @Autowired
    private SaveDataUtil saveDataUtil;

    private static final Logger log = LoggerFactory.getLogger(BeiJingService.class);

    public void start() {
        String url = "http://58.30.229.134/monitor-pub/text_result.do";
        try {
            Document document = FormateConnection.createConnection(Jsoup.connect(url))
                    .data("pageIndex", "1")
                    .post();
            log.info("当前页面--{}", url);
            Elements allElements = document.getAllElements();
            String total = allElements.select("#total").attr("value");
            partClickNext(total);
        } catch (Exception e) {
            log.error("{}--{}", url, e.getMessage());
        } finally {
            log.info("数据爬取结束");
        }


    }

    private void partClickNext(String total) {
        //   List<String> urlList = new ArrayList<>();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        for (int i = 1; i <= parseInt(total); i++) {
            String url = "http://58.30.229.134/monitor-pub/text_result.do";
            try {
                Document document = FormateConnection.createConnection(Jsoup.connect(url))
                        .data("pageIndex", i + "")
                        .post();
                log.info("当前页面--{}", url);

                document.select("#form1 > div.search_wrap > div.search_list > ul li").forEach(l -> {
                    JSONObject jsonObject = new JSONObject();
                    String mark = l.getElementsByTag("a").get(1).text();
                    if (mark.isEmpty()) {
                        String id = l.getElementsByTag("a").get(0).attr("href");
                        try {
                            if (!StringUtils.isEmpty(id)) {
                                Document documentNew = FormateConnection.createConnection(Jsoup.connect("http://58.30.229.134/monitor-pub/org_jbxx/" + id.split("/")[3]))
                                        .get();
                                jsonObject.put("type", documentNew.getAllElements().select("body > div.outer > div.company.m_auto > div.com_prof > table > tbody > tr:nth-child(1) > td:nth-child(4)").text());
                                jsonObject.put("address", documentNew.getAllElements().select("body > div.outer > div.company.m_auto > div.com_prof > table > tbody > tr:nth-child(2) > td:nth-child(4)").text());
                                jsonObject.put("industry", documentNew.getAllElements().select("body > div.outer > div.company.m_auto > div.com_prof > table > tbody > tr:nth-child(4) > td:nth-child(4)").text());
                                jsonObject.put("href", "http://58.30.229.134/monitor-pub/org_zdjc/" + id.split("/")[3]);
                                jsonObjectList.add(jsonObject);
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }

                        /*if (!StringUtils.isEmpty(id)) {
                            urlList.add("http://58.30.229.134/monitor-pub/org_zdjc/" + id.split("/")[3]);
                        }*/
                    }

                });
            } catch (Exception e) {
                log.error("{}--{}", url, e.getMessage());
                continue;
            }
        }
        getDetailData(jsonObjectList);
    }

    private void getDetailData(List<JSONObject> jsonObjectList) {
        for (JSONObject jsonObject : jsonObjectList) {

            try {
                Document document = FormateConnection.createConnection(Jsoup.connect(jsonObject.getString("href")))
                        .get();
                log.info("当前页面--{}", jsonObject.getString("href"));
                Elements allElements = document.getAllElements();
                String total = allElements.select("#total").attr("value");
                String entName = allElements.select("body > form > div > div.m_auto.logo_top > div.com_tit_new.f_22.clr_3").text();
                detailClickNext(jsonObject, total, entName);
            } catch (Exception e) {
                log.error("{}--{}", jsonObject.getString("href"), e.getMessage());
                continue;
            }
        }

    }


    private void detailClickNext(JSONObject jsonObject, String total, String entName) {
        List<MonitorDataTag> lastPoint = monitorDataTagDAO.findByProvinceAndUniqueKey(province, entName);
        String date;
        List<String> stringList = new ArrayList<>();
        if (lastPoint.isEmpty()) {
            date = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            stringList.add(date);
        } else {
            date = LocalDate.parse(lastPoint
                    .stream()
                    .max((p, p2) -> (p.getLabel().compareTo(p2.getLabel())))
                    .get().getLabel(), DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                    .toString();
            String nowdays = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            if (!date.equals(LocalDate.now().minusDays(1).toString())) {
                do {
                    String dateRange = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(1).toString();
                    date = dateRange;
                    stringList.add(dateRange);
                    if (dateRange.equals(nowdays)) {
                        return;
                    }
                } while (true);

            } else {
                stringList.add(nowdays);
            }

        }

        for (String s : stringList) {
            List<MonitorData> monitorDataList = new ArrayList<>();
            for (int i = 1; i <= parseInt(total); i++) {
                try {
                    Document document = FormateConnection.createConnection(Jsoup.connect(jsonObject.getString("href")))
                            .data("startTime", s)
                            .data("pageIndex", i + "")
                            .post();
                    log.info("当前页面--{}", jsonObject.getString("href"));
                    // List<String> entIds = new ArrayList<>();
                    Elements allElements = document.getAllElements();
                    saveDetailData(allElements, monitorDataList, jsonObject);
                } catch (Exception e) {
                    log.error("{}--{}", jsonObject.getString("href"), e.getMessage());
                    continue;
                }
            }
            saveDataUtil.saveTag(monitorDataList, province);

        }


    }

    private void saveDetailData(Elements allElements, List<MonitorData> monitorDataList, JSONObject jsonObject) {
        String name = allElements.select("body > form > div > div.m_auto.logo_top > div.com_tit_new.f_22.clr_3").text();

        Elements elements = allElements.select("body > form > div > div.company.m_auto > div > div.find.m_auto > div > div > table > tbody > tr:nth-child(n+2)");


        if (!elements.text().equals("暂无数据！")) {
            for (Element e : elements) {
                MonitorData monitorData = new MonitorData();
                monitorData.setId(UUID.randomUUID().toString());
                monitorData.setCompanyName(name);
                monitorData.setMonitorPoint(e.getElementsByTag("td").get(1).attr("title"))
                        .setMonitorTime(e.getElementsByTag("td").get(2).text())
                        .setMonitorInfo(e.getElementsByTag("td").get(3).text())
                        .setMonitorValue(e.getElementsByTag("td").get(4).text())
                        .setMonitorStandardValue(e.getElementsByTag("td").get(5).text())
                        .setOverproof(e.getElementsByTag("td").get(7).text())
                        .setProvince(province)
                        .setAddress(jsonObject.getString("address"))
                        .setIndustry(jsonObject.getString("industry"))
                        .setPollutionType(jsonObject.getString("type"))
                        .setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                monitorDataList.add(monitorData);

            }

        }
    }

}
